import { Injectable } from '@nestjs/common';

@Injectable()
export class RoomService {
    public rooms: Room[] = [];
    constructor() { }
    getRooms(): Room[] {
        return this.rooms
    }
    createRoom(name: string, owner: string, maxUsers:number): Room {
        const room = new Room(name, owner, maxUsers);
        room.addUser(owner);
        this.rooms.push(room);
        return room;
    }
    entryRoom(name: string, user: string): Room {
        const room = this.rooms.find(room => room.name === name);
        if (room) {
            if (room.isfull) {
                throw new Error('Room is full');
            }
            room.addUser(user);
            return room;
        }
        return null;
    }
    leaveRoom(name: string, user: string): Room {
        const room = this.rooms.find(room => room.name === name);
        if (room) {
            room.removeUser(user);
            if (room.isEmpty()) {
                this.rooms = this.rooms.filter(room => room.name !== name);
            }
            return room;
        }
        return null;
    }

}


class Room {

    constructor(public name: string, public owner: string, public maxUsers: number = 10, public users: string[] = []) { }
    getRoom(): Room {
        return this;
    }
    addUser(user: string): Room {
        this.users.push(user);
        return this;
    }
    removeUser(user: string): Room {
        this.users = this.users.filter(u => u !== user);
        return this;
    }
    isEmpty(): boolean {
        return this.users.length === 0;
    }
    isfull(): boolean {
        return this.users.length === this.maxUsers;
    }

}